<template>
  <a-modal @cancel="close" title="创建换车单" width="75vw" v-model:visible="visible" unmount-on-close>
    <div class="time-wrapper">
      <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
        <page-form-row>
          <page-form-item label="订单类型" size="1">
            <a-radio-group v-model="form.refType" @change="orderTypesRadioChange" :disabled="form?.type === 'order'">
              <a-radio :value="item.value" v-for="item in orderTypes" :key="item.value">
                {{ item.label }}
              </a-radio>
            </a-radio-group>
          </page-form-item>
          <page-form-item field="refId" label="选择订单号" required size="1/3">
            <remote-select
              v-model="form.refId"
              type="all_replace_order_list"
              :params="{
                refType: form.refType,
              }"
              @change="orderListChange"
              @initList="initList"
              :disabled="form?.type === 'order'"
            />
          </page-form-item>
          <page-form-item field="workOperatorId" label="换车人" required size="1/3">
            <remote-select
              :disabled="!form.refId"
              v-model="form.workOperatorId"
              :params="{
                siteIdList: [carSiteId],
                updateVp: updateVp,
              }"
              @change="operatorListChange"
              type="reassignment_staff_list_multiple"
            />
          </page-form-item>
          <page-form-item field="expectEndTime" label="换车时间" required size="1/3">
            <i-date-picker
              show-time
              value-format="YYYY-MM-DD HH:mm:ss"
              class="w-full"
              v-model="form.expectEndTime"
              popup-container=".time-wrapper"
            />
          </page-form-item>
        </page-form-row>
        <div class="order-info">
          <div class="tlt">订单信息</div>
          <a-descriptions v-if="form.refId && orderInfoMsg" :size="'medium'" :align="{ label: 'right' }">
            <a-descriptions-item label="预计租赁周期">{{ orderInfoMsg.startTime }} 至 {{ orderInfoMsg.endTime }}</a-descriptions-item>
            <a-descriptions-item label="租期">{{ orderInfoMsg.rentDays }}</a-descriptions-item>
            <a-descriptions-item label="订单来源">{{ orderInfoMsg.orderSourceName }}</a-descriptions-item>
            <a-descriptions-item label="车型">{{ orderInfoMsg.carModelName }}</a-descriptions-item>
            <a-descriptions-item label="交车车型">{{ orderInfoMsg.originalModelName }}</a-descriptions-item>
            <a-descriptions-item label="交车车牌号">{{ orderInfoMsg.carLicenseNo }}</a-descriptions-item>
          </a-descriptions>
          <a-empty v-else description="暂无订单信息，请先选择订单号" />
        </div>
        <div class="line"></div>
        <div style="margin: 10px; color: #1d2129; font-size: 16px; font-weight: 500">换上车信息</div>
        <page-form-row>
          <page-form-item label="车辆来源" size="1/3">
            <a-radio-group v-model="form.carSource" @change="carFromsRadioChange">
              <a-radio :value="item.value" v-for="item in carFroms" :key="item.value">
                {{ item.label }}
              </a-radio>
            </a-radio-group>
          </page-form-item>
          <page-form-item field="carLicenseNo" label="车牌号" size="1/3">
            <a-select v-model="form.carLicenseNo" placeholder="请选择" @click="platoonCarFn" :popup-visible="false" />
          </page-form-item>
          <page-form-item field="carModelId" label="车型" size="2/3">
            <div class="car-model">{{ form.carModelName || '-' }}</div>
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" @click="handleBeforeOk" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>
  <!-- 选车牌 -->
  <car-selector :title="carSelectorModalTitle" mode="select" ref="carSelectorRef" @confirm="carConfirmFn" />
</template>

<script setup name="carWarehousingModalRef">
  import carSelector from '@/views/assets/car/stock/car-selector.vue'
  import { createReplaceCarWork } from '@/api/business/workorder'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'
  import { ref } from 'vue'
  // emit 事件
  const emit = defineEmits(['ok', 'close'])
  const noFormSubmit = ref(false)
  const visible = ref(false)
  const orderInfo = ref({})
  const isChooseCarId = ref(null) //换下车
  const orderInfoMsg = ref()
  const siteIdList = ref(null) //选择换车人的归属门店list
  const carSiteId = ref(null) //选择车辆后的归属门店
  const updateVp = ref(0)
  const form = ref({
    refType: 1,
    carSource: 1,
  })
  const rules = {
    refId: [{ required: true, message: '请选择订单' }],
    workOperatorId: [{ required: true, message: '请选择换车人' }],
    expectEndTime: [{ required: true, message: '请选择换车时间' }],
  }

  // 订单类型
  const orderTypes = ref([
    { value: 1, label: '短租订单' },
    { value: 2, label: '长租订单' },
  ])
  const orderTypesRadioChange = (e) => {
    orderInfoMsg.value = undefined
    form.value = {
      refId: undefined,
      refCode: undefined,
      siteId: undefined,
      workOperatorId: undefined,
      expectEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),

      carSource: 1,
      carId: undefined,
      carLicenseNo: undefined,
      carModelId: undefined,
      carModelName: undefined,
    }
    form.value.refType = e
  }
  // 选择人
  const operatorListChange = (_, option = {}) => {
    siteIdList.value = option.siteIdList
    console.log(option)
    console.log(siteIdList.value)
    console.log(carSiteId.value)
    if (form.value.carId) {
      const hasValue = siteIdList.value.indexOf(Number(carSiteId.value))
      console.log(hasValue)
      // 如先选择负责人，在选车，然后变更负责人，需判断负责人和车辆的门店是否符合，是则支持创建，否则自动清理车辆，需重新选择
      if (hasValue == -1) {
        form.value.carId = undefined
        form.value.carLicenseNo = undefined
        form.value.carModelId = undefined
        form.value.carModelName = undefined
      }
    }
  }
  // 车辆来源
  const carFroms = ref([
    { value: 1, label: '门店车辆' },
    { value: 3, label: '跨门店调车' },
  ])
  const carFromsRadioChange = (e) => {
    console.log(e)
    form.value.carSource = e

    form.value.carId = undefined
    // form.value.siteId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
    console.log(form.value)
  }
  const initList = (options = []) => {
    const option = options.find((item) => item.orderId == form.value.refId) || {}
    console.log('option', option, form.value)
    orderInfoMsg.value = option
  }
  const orderListChange = (_, option = {}) => {
    orderInfoMsg.value = option
    console.log('option', option)
    form.value.workOperatorId = undefined
    form.value.carSource = 1
    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
    form.value.expectEndTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

    isChooseCarId.value = option.carId //换下车（排车图打开时默认选中

    form.value.refId = option.orderId
    form.value.refCode = option.orderCode
    form.value.returnCarTime = option.endTime //订单预还，选择车牌用
    form.value.siteId = option.siteId //选完订单选人用
    carSiteId.value = option.siteId
    if (option.orderSource == 2 && !option.carId) {
      Message.error('您选择的订单匹配的车辆为渠道车辆，请先同平台车辆匹配后再换车')
      noFormSubmit.value = true
    } else {
      noFormSubmit.value = false
    }
  }

  const open = (record) => {
    console.log('record', record)
    form.value = {
      refType: record?.orderType || 1,
      expectEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),

      returnCarTime: record?.endTime || undefined,

      refId: record?.id || undefined,
      refCode: record?.orderCode || undefined,
      siteId: record?.siteId || undefined,
      workOperatorId: undefined,

      carSource: record?.carSource || 1,
      carId: undefined,
      carLicenseNo: undefined,
      carModelId: undefined,
      carModelName: undefined,
      type: record?.type || undefined,
      returnCarTime: record?.returnCarTime || undefined,
    }

    // 订单跳转过来需要默认选中当前车辆
    if (record?.carId) {
      isChooseCarId.value = record?.carId
    }
    visible.value = true
  }
  // 排车 & 改排
  const carSelectorRef = ref()
  const carSelectorModalTitle = ref('选择车牌号')
  const platoonCarFn = () => {
    if (!form.value.refId) {
      Message.error('请选择订单号')
      return false
    }
    let startTime = form.value.expectEndTime
    const endTime = form.value.returnCarTime
    if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
      // 将开始时间设置为实际开始时间
      startTime = orderInfoMsg.value.startTime
    }
    carSelectorRef.value.open(
      {
        id: form.value.carId ? form.value.carId : undefined,
        carSource: form.value.carSource,
        dateRange: [startTime, endTime],
      },
      {
        siteId: orderInfoMsg.value.siteId,
        startTime: dayjs().format('YYYY-MM-DD 00:00:00'), //预取
        endTime: form.value.returnCarTime, //预还
        platoonCarId: isChooseCarId.value, //占用被换车
      }
    )
  }
  // 选择车牌完成后
  // 记录弹窗queryParam
  const carConfirmFn = (id, option = {}, queryParam) => {
    console.log('选完车queryParam', queryParam)
    form.value.carId = id
    form.value.carLicenseNo = option.licenseNo
    form.value.carModelId = option.modelId
    form.value.carModelName = option.modelName
    carSiteId.value = Number(queryParam.siteId)
    if (form.value.carSource == 3 && form.value.workOperatorId) {
      console.log('选择跨门店，有换车人时')
      console.log(siteIdList.value)
      console.log(queryParam.siteId)
      const hasValue = siteIdList.value.indexOf(Number(queryParam.siteId))
      console.log(hasValue)
      // 如先选择人后选择车辆，同时跨门店调车，之前选择的换车人数据权限不符合车辆的归属门店，则自动清空
      // 需重新选择，此时下拉展示选择车辆归属门店符合数据权限的在职员工
      if (hasValue == -1) {
        form.value.workOperatorId = undefined
        form.value.realname = undefined
      }
    }
    if (form.value.carSource == 3) {
      carSiteId.value = Number(queryParam.siteId)
      updateVp.value++
    }
  }
  // 关闭
  const close = () => {
    visible.value = false
    emit('close')
  }
  const formRef = ref()
  const okLoading = ref(false)
  const validateFn = () => {
    okLoading.value = true
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          okLoading.value = false
          console.log(error)
          reject()
        } else {
          resolve()
        }
      })
    })
  }
  const handleBeforeOk = (done) => {
    if (noFormSubmit.value == true) {
      Message.error('您选择的订单匹配的车辆为渠道车辆，请先同平台车辆匹配后再换车')
      return false
    }
    return new Promise((resolve, reject) => {
      validateFn().then(() => {
        createReplaceCarWork({ ...form.value })
          .then((res) => {
            console.log(res)
            Message.success(res.message)
            emit('ok')
            visible.value = false
            done()
            resolve()
          })
          .finally(() => {
            okLoading.value = false
          })
      })
    })
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  :deep(.arco-row) {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  :deep(.arco-modal-body) {
    padding: 10px 80px !important;
  }
  :deep(.arco-col) {
    padding: 0 10px !important;
  }
  :deep(.arco-form-item) {
    margin-bottom: 5px !important;
  }
  :deep(.arco-picker-container) {
    margin-top: 30px;
    margin-left: 20px;
  }
  .form-items {
    margin: 16px 10px;
  }
  .car-model {
    padding: 12px;
    width: 100%;
    background: #f7f8fa;
    color: #1d2129;
    font-weight: 400;
    font-size: 14px;
  }
  .line {
    width: calc(100% - 20px);
    height: 1px;
    background: #f2f3f5;
    margin: 10px 10px 0;
  }
  .order-info {
    background: #f7f8fa;
    padding: 20px;
    margin: 12px;
    .tlt {
      font-size: 16px;
      color: #1d2129;
      font-weight: 500;
    }
  }
</style>
